<template>
  <!-- <div>
    添加子部门, {{ showDialog }}
  </div> -->

  <!-- 点击x，会触发close事件 -->
  <el-dialog
    :title="(isEdit ? '编辑' : '添加') + '子部门'"
    :visible="showDialog"
    @close="hClose"
  >
    <el-form ref="refForm" label-width="100px" :model="formData" :rules="rules">
      <el-form-item prop="name" label="部门名称">
        <el-input
          v-model="formData.name"
          placeholder="2-10个字符"
          style="width: 80%"
          size="mini"
        />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input
          v-model="formData.code"
          placeholder="2-10个字符"
          style="width: 80%"
          size="mini"
        />
      </el-form-item>
      <el-form-item prop="managerId" label="部门负责人">
        <el-select
          v-model="formData.managerId"
          placeholder="请选择负责人"
          style="width: 80%"
          size="mini"
        >
          <!-- 下拉选项 循环 负责人数据 label表示显示的字段 value 存储字段 -->
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input
          v-model="formData.introduce"
          placeholder="1-100个字符"
          type="textarea"
          size="mini"
          :rows="4"
          style="width: 80%"
        />
      </el-form-item>
      <el-form-item>
        <!-- 按钮 -->
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button
              size="mini"
              type="primary"
              @click="hSave"
            >确定</el-button>
            <el-button size="mini" @click="hClose">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import {
  getDepartment,
  getDepartmentManager,
  addDepartment,
  getDepartmentDetail,
  updateDepartment
} from '@/api/department'

export default {
  props: {
    isEdit: {
      type: Boolean
    },
    // 由父组件来控制显示和隐藏
    showDialog: {
      type: Boolean
    },
    // 子组件接收curNodeId
    curNodeId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      currentNodeId: null, // 存储当前点击的id
      managerList: [],
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称是2-10位哦', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 1.发请求拿到已有部门的名称
              const res = await getDepartment()
              // console.log('部门名称已存在')
              // 遍历部门名称，对比是否有重复的
              let data = res.data

              // 如果当前是编辑状态，首先从data 中排出自己
              if (this.isEdit) {
                data = res.data.filter((item) => item.id !== this.curNodeId)
              }

              // 判断部门名称是否存在
              if (data.find((item) => item.name === value)) {
                callback(new Error('部门名称[' + value + ']已存在,请更换'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '部门编码的长度为2-10个字符',
            trigger: 'blur'
          },
          {
            validator: async(rule, value, callback) => {
              // 1.发请求拿到已有部门的编码
              const res = await getDepartment()
              // console.log('部门名称已存在')
              // 遍历部门编码，对比是否有重复的
              let data = res.data

              // 如果当前是编辑状态，首先从data 中排出自己
              if (this.isEdit) {
                data = res.data.filter((item) => item.id !== this.curNodeId)
              }

              // 判断部门编码是否存在
              if (data.find((item) => item.code === value)) {
                callback(new Error('部门编码[' + value + ']已存在,请更换'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ], // 部门编码
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '部门介绍的长度为1-100个字符',
            trigger: 'blur'
          }
        ], // 部门介绍
        managerId: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadDepartmentManager()
  },
  methods: {
    async getDetail() {
      // console.log('子组件获取数据')
      const res = await getDepartmentDetail(this.curNodeId)
      // console.log('哈哈哈', res。data)
      this.formData = res.data
    },
    async doAdd() {
      // 调用 api
      await addDepartment({ ...this.formData, pid: this.curNodeId })
      // 提醒添加成功
      this.$message.success('恭喜您，添加成功！')
      // 调用函数关闭弹窗并且清空表单数据
      this.hClose()
      // 通知父组件更新数据
      this.$emit('updateManager')
    },
    async doEdit() {
      // 调用 api
      await updateDepartment(this.formData)
      // 提醒添加成功
      this.$message.success('恭喜您，修改成功！')
      // 调用函数关闭弹窗并且清空表单数据
      this.hClose()
      // 通知父组件更新数据
      this.$emit('updateManager')
    },
    hSave() {
      // 兜底校验
      this.$refs.refForm.validate((valid) => {
        this.isEdit ? this.doEdit() : this.doAdd()
        // if (this.isEdit) {
        //   this.doEdit()
        // } else {
        //   this.doAdd()
        // }
      })
    },
    async loadDepartmentManager() {
      const res = await getDepartmentManager()
      // console.log(res)
      this.managerList = res.data
    },

    hClose() {
      // 当用户先点击编辑在添加的时候,多传输很多无用的值，可能会出现bug，所以要清空表单
      this.formData = {
        code: '',
        introduce: '',
        managerId: '',
        name: ''
      }
      // console.log('用户点击关闭x')
      // 通知父组件修改showDialog
      this.$emit('update:showDialog', false)
      // 清空表单
      this.$refs.refForm.resetFields()
    }
  }
}
</script>
